const { getUserTaskSetting, saveUserTaskSetting } = require('../../../utils/task');

function pad(n) { return n < 10 ? '0' + n : '' + n; }

Page({
  data: {
    task: {},
    remindEnabled: false,
    remindList: [],
    remindTypeOptions: [],
    timeSelectorRange: [[], [], []], // [小时, 分钟, 秒]
  },
  async onLoad(options) {
    const userTaskId = options.userTaskId;
    this.initTimeSelectorRange();
    await this.loadTaskAndRemind(userTaskId);
  },
  initTimeSelectorRange() {
    const hours = [], minutes = [], seconds = [];
    for (let i = 0; i < 24; i++) hours.push(pad(i));
    for (let i = 0; i < 60; i++) minutes.push(pad(i));
    for (let i = 0; i < 60; i++) seconds.push(pad(i));
    this.setData({ timeSelectorRange: [hours, minutes, seconds] });
  },
  async loadTaskAndRemind(userTaskId) {
    let task = { taskName: '我的任务', userTaskId: userTaskId, checkInStartTime: '08:00:00' };
    let remindEnabled = false;
    let remindTypeOptions = [];
    let remindList = [];
    try {
      const res = await getUserTaskSetting(userTaskId);
      task.taskName = res.taskName || task.taskName;
      task.checkInStartTime = res.checkInStartTime;
      task.id= res.id
      remindEnabled = res.remindFlag === 'yes';
      remindTypeOptions = res.remindMethodList || [
        { label: '站内通知', value: 'message', checked: true, disabled: true, visible: true },
        { label: '短信', value: 'sms', checked: false, disabled: false, visible: true },
        { label: '邮箱', value: 'email', checked: false, disabled: false, visible: true }
      ];
      remindList = (res.remindList || []).map(item => this.enhanceRemindItem(item));
    } catch (e) {
      console.error('获取我的任务设置异常！！', e)
    }
    this.setData({ task, remindEnabled, remindTypeOptions, remindList });
  },
  enhanceRemindItem(item) {
    // item.time: "HH:mm:ss"
    let timeArr = (item.time || '08:00:00').split(':').map(Number);
    return {
      ...item,
      timeSelectorValue: [timeArr[0], timeArr[1], timeArr[2]]
    };
  },
  getDefaultRemindTime(startTime) {
    const [h, m, s] = startTime.split(':').map(Number);
    let minutes = h * 60 + m - 5;
    if (minutes < 0) minutes += 24 * 60;
    const hh = Math.floor(minutes / 60).toString().padStart(2, '0');
    const mm = (minutes % 60).toString().padStart(2, '0');
    return `${hh}:${mm}:00`;
  },
  onRemindSwitchChange(e) {
    this.setData({ remindEnabled: e.detail.value });
  },
  onGlobalRemindTypeChange(e) {
    const values = e.detail.value;
    const remindTypeOptions = this.data.remindTypeOptions.map(opt => {
      if (opt.value === 'message') return { ...opt, checked: true };
      return { ...opt, checked: values.includes(opt.value) };
    });
    this.setData({ remindTypeOptions });
  },
  onAddRemind() {
    // 判断超过3个就不允许添加
    if (this.data.remindList && this.data.remindList.length > 2) {
      wx.showToast({ title: '提醒不允许添加超过3个', icon: 'error' });
      return
    }
    const defaultTime = this.getDefaultRemindTime(this.data.task.checkInStartTime);
    const timeArr = (defaultTime || '08:00:00').split(':').map(Number);
    this.setData({
      remindList: this.data.remindList.concat({
        id: Date.now(),
        time: defaultTime,
        timeSelectorValue: [timeArr[0], timeArr[1], timeArr[2]],
        content: ''
      })
    });
  },
  onRemoveRemind(e) {
    const idx = e.currentTarget.dataset.index;
    const list = this.data.remindList.slice();
    list.splice(idx, 1);
    this.setData({ remindList: list });
  },
  onRemindTimeChange(e) {
    const idx = e.currentTarget.dataset.index;
    const val = e.detail.value;
    const range = this.data.timeSelectorRange;
    const h = range[0][val[0]], m = range[1][val[1]], s = range[2][val[2]];
    const time = `${h}:${m}:${s}`;
    const list = this.data.remindList.slice();
    list[idx].time = time;
    list[idx].timeSelectorValue = val;
    this.setData({ remindList: list });
  },
  onRemindContentInput(e) {
    const idx = e.currentTarget.dataset.index;
    const value = e.detail.value;
    const list = this.data.remindList.slice();
    list[idx].content = value;
    this.setData({ remindList: list });
  },
  onSaveSetting: async function() {
    const payload = {
      id: this.data.task.id,
      userTaskId: this.data.task.userTaskId,
      remindFlag: this.data.remindEnabled ? 'yes' : 'no',
      remindMethodList: this.data.remindEnabled ? this.data.remindTypeOptions.map(opt => ({
        label: opt.label,
        value: opt.value,
        checked: opt.checked,
        disabled: opt.disabled,
        visible: opt.visible
      })) : null,
      remindList: this.data.remindEnabled ? this.data.remindList.map(item => ({
        id: item.id,
        time: item.time,
        content: item.content
      })) : null
    };
    try {
      await saveUserTaskSetting(payload.userTaskId, payload);
      wx.showToast({ title: '保存成功', icon: 'success' });
      setTimeout(() => {
        wx.navigateBack();
      }, 600);
    } catch (e) {
      wx.showToast({ title: '保存失败', icon: 'error' });
      console.error('保存任务设置失败', e);
    }
  }
}); 